﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Net;

namespace Apewer.Web
{

    /// <summary></summary>
    public class HttpListener
    {

        private System.Net.HttpListener _listener;
        private Thread _thread;
        private string _prefix = "http://*:0/";

        /// <summary></summary>
        public Action<HttpListenerContext> Action { get; set; }

        /// <summary></summary>
        public string Prefix
        {
            get { return _prefix; }
            set { _prefix = value ?? ""; }
        }

        /// <summary></summary>
        public Exception Start()
        {
            var prefix = Prefix;
            Logger.Web.Info(this, $"准备在 {Prefix} 启动。");

            _listener = new System.Net.HttpListener();
            try
            {
                _listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
                _listener.Prefixes.Add(prefix);
                _listener.Start();

                // 多线程方式处理请求。
                // _thread = new Thread(Listen);
                // _thread.IsBackground = true;
                // _thread.Start();

                // 异步方式处理请求。
                _listener.BeginGetContext(Received, null);

                Logger.Web.Info(this, $"已在 {prefix} 启动。");
                return null;
            }
            catch (Exception ex)
            {
                Logger.Web.Exception(ex, this);
                Logger.Web.Info(this, $"在 {prefix} 启动失败。");
                return ex;
            }
        }

        /// <summary></summary>
        public void Stop()
        {
            if (_thread != null)
            {
                // _thread.Abort();
                _thread = null;
            }

            if (_listener != null)
            {
                _listener.Close();
                _listener.Stop();
                _listener = null;
            }
        }

        void Received(IAsyncResult ar)
        {
            _listener.BeginGetContext(Received, null);

            var context = _listener.EndGetContext(ar);
            var action = Action;
            if (action != null) action(context);
        }

        void Listen()
        {
            while (true)
            {
                if (_listener == null) break;

                var context = _listener.GetContext();
                var action = Action;
                if (action == null) continue;
                action(context);
                // RuntimeUtility.InBackground(() => action(context), true);
            }
        }

    }

}
